<template>
    <div>
        <div class="top-panel">
            <el-card>
                <el-form :model="searchForm" label-width="70px" label-position="right">
                    <el-row>
                        <el-col :span="5">
                            <el-form-item label="名称">
                                <el-input class="password-input" v-model="searchForm.nameFuzzy" clearable
                                    placeholder="支持模糊搜索" @keyup.enter.native="loadDataList"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="描述">
                                <el-input class="password-input" v-model="searchForm.descriptionFuzzy" clearable
                                    placeholder="支持模糊搜索" @keyup.enter.native="loadDataList"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="状态">
                                <el-select v-model="searchForm.status" placeholder="请选择状态">
                                    <el-option label="下架" :value="0"></el-option>
                                    <el-option label="上架" :value="1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="审核状态">
                                <el-select v-model="searchForm.auditStatus" placeholder="请选择状态">
                                    <el-option label="待审核" :value="0"></el-option>
                                    <el-option label="通过" :value="1"></el-option>
                                    <el-option label="不通过" :value="2"></el-option>

                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" :style="{ paddingLeft: '10px' }">
                            <el-button type="success" @click="loadDataList()">查询</el-button>
                            <el-button type="info" @click="reset()">重置</el-button>
                            <el-button type="primary" @click="openAddOrUpdata(null)">新增</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </div>
        <el-card class="table-data-card">
            <template #header>
                <span>菜品列表</span>
            </template>
            <Table ref="tableInfoRef" :columns="columns" :fetch="loadDataList" :dataSource="tableData"
                :options="tableOptions" :extHeight="tableOptions.extHeight" @row-click="handleRowClick">
                <template #operation="{ index, row }">
                    <div class="row-op-panel">
                        <!-- 审核操作 -->
                        <a class="a-link" style="color: red;" href="javascript:void(0)" v-if="row.auditStatus === 2"
                            @click.prevent="handleAudSubmit(row.id)">
                            不通过
                        </a>
                        <a class="a-link" href="javascript:void(0)" v-if="row.auditStatus === 1"
                            @click.prevent="dishesStatus(row.id, row.status === 1 ? 0 : 1)">
                            {{ row.status === 1 ? '下架' : '上架' }}
                        </a>
                        <a class="a-link" href="javascript:void(0)" @click.prevent="openAddOrUpdata(row)">编辑</a>
                        <a class="a-link" href="javascript:void(0)" @click.prevent="delDishesBtn(row.id)">删除</a>
                    </div>
                </template>
            </Table>
        </el-card>

        <FormDialog ref="formDialogRef" :title="dialogTitle" :form-model="formModel" :rules="rules"
            @submit="handleSubmit" @closed="resetTempFlavor">
            <el-form-item label="菜品分类" prop="categoryId">
                <el-select v-model="formModel.categoryId" placeholder="请选择分类">
                    <el-option v-for="(item, index) in categoriesData" :label="item.name" :value="item.id"
                        :key="index"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="菜品名称" prop="name">
                <el-input v-model="formModel.name" placeholder="请输入菜品名称" />
            </el-form-item>

            <el-form-item label="口味">
                <el-button @click="addFlavors()">＋</el-button>
            </el-form-item>

            <el-form-item label="描述" prop="description">
                <el-input type="textarea" v-model="formModel.description" placeholder="请输入描述" :rows="3" />
            </el-form-item>

            <el-form-item label="排序" prop="sortOrder">
                <el-input-number v-model="formModel.sortOrder" :min="0" :step="1" placeholder="请输入排序值" />
            </el-form-item>

            <el-form-item label="原价" prop="originalPrice">
                <el-input-number v-model="formModel.originalPrice" :precision="2" :step="0.1" :max="9999" :min="0" />
            </el-form-item>

            <el-form-item label="现价" prop="price">
                <el-input-number v-model="formModel.price" :precision="2" :step="0.1" :max="9999" :min="0" />
            </el-form-item>

            <el-form-item label="库存" prop="stock">
                <el-input-number v-model="formModel.stock" :min="0" :max="999999" />
            </el-form-item>

            <el-form-item label="图片">
                <el-upload action="#" list-type="picture-card" :auto-upload="false" v-model:file-list="fileList"
                    :drag="true">
                    <el-icon>
                        <Plus />
                    </el-icon>

                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <el-icon>
                                        <ZoomIn />
                                    </el-icon>
                                </span>
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img style="width: 100%;" :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>

        </FormDialog>


        <!-- 口味选择 -->
        <FormDialog ref="formDialogFlaRef" :title="dialogFlaTitle" :form-model="tempFlavorModel" :rules="flavorRules"
            @submit="handleFlaSubmit">
            <el-form-item label="口味名称" prop="name">
                <el-input v-model="tempFlavorModel.name" placeholder="请输入口味名称" />
            </el-form-item>

            <el-form-item label="口味值" prop="values">
                <div v-for="(val, index) in tempFlavorModel.values" :key="index"
                    style="display:flex; align-items:center; margin-bottom:6px;">
                    <el-input v-model="tempFlavorModel.values[index]" placeholder="请输入口味值" style="flex:1;" />
                    <el-button @click="removeFlavorValue(index)">－</el-button>
                </div>
                <el-button style="margin-top: -5px; margin-left: 2px;" @click="addFlavorValue">＋</el-button>
            </el-form-item>

            <el-form-item label="状态" prop="isRequired">
                <el-select v-model="tempFlavorModel.isRequired" placeholder="是否必选">
                    <el-option label="可选" :value="0"></el-option>
                    <el-option label="必选" :value="1"></el-option>
                </el-select>
            </el-form-item>
        </FormDialog>

        <!-- 审核表单 -->
        <FormDialog ref="formDialogAudRef" :title="dialogAudTitle" :form-model="AuditModel" :rules="AuditRules"
            @submit="handleAuditSubmit">
            <el-form-item label="审核状态" prop="auditStatus">
                <el-select v-model="AuditModel.auditStatus" placeholder="选择审核状态" disabled>
                    <el-option label="通过" :value="1"></el-option>
                    <el-option label="不通过" :value="2"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="审核备注" prop="auditRemark">
                <el-input type="textarea" v-model="AuditModel.auditRemark" placeholder="请输入审核备注" :rows="3" disabled />
            </el-form-item>
        </FormDialog>

    </div>
</template>
<script setup>

import FormDialog from '@/components/FormDialog.vue';
import { getCurrentInstance, nextTick, ref } from 'vue';
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'

import axios from 'axios'


const { proxy } = getCurrentInstance()

const searchForm = ref({})
const tableData = ref({})
// 分类数据列表
const categoriesData = ref([])

const formDialogAudRef = ref(null)
const dialogAudTitle = ref('')
// 审核列表数据
const AuditModel = ref({})

// 临时口味表单数据
const tempFlavorModel = ref({
    name: '',
    isRequired: 0,
    values: []
})

const tableOptions = ref({
    extHeight: 125
})

const api = {
    // 获取分类列表
    getCategories: '/tuanCategories/loadDataList',
    // 获取菜品列表
    loadDataList: '/tuanDishes/loadDataList',
    // 新增、修改菜品表
    addOrUpdate: '/tuanDishes/addOrUpdate',
    // 上传附件
    uploadFile: '/api/file/uploadFile',
    // 菜品上架
    enable: '/tuanDishes/enable',
    // 菜品下架
    disable: '/tuanDishes/disable',
    // 获取审核信息
    getAudit: '/tuanDishesAudit/getAudit',
    // 删除菜品
    delDishes: '/tuanDishes/delDishes',
}

const columns = [
    {
        label: "商家",
        prop: "merchantId",
    },
    {
        label: "分类名称",
        prop: "nameCateName",
    },
    {
        label: "菜品名称",
        prop: "name",
    },
    {
        label: "菜品描述",
        prop: "description",
    },
    {
        label: "菜品价格",
        prop: "price",
    },
    {
        label: "原价",
        prop: "originalPrice",
    },
    {
        label: "状态",
        prop: "statusName",
    },
    {
        label: "库存",
        prop: "stock",
    },
    {
        label: "审核状态",
        prop: "auditStatusName",
    },
    {
        label: "创建时间",
        prop: "createdAt",
    },
    {
        label: "更新时间",
        prop: "updatedAt",
    },
    {
        width: 150,
        label: "操作",
        scopedSlots: "operation"
    }
]

// 重置菜品表单
const resetFormModel = () => {
    formModel.value = {
        sortOrder: 0,
        name: '',
        description: '',
        price: 0,
        originalPrice: 0,
        stock: 1,
        flavors: {
            values: []
        }
    }
    fileList.value = []       // 清空图片列表
    deletedFiles.value = []   // 清空删除列表
    tempFlavorModel.value = {
        name: '',
        isRequired: 0,
        id: null,
        dishId: null,
        values: []
    }
}

const resetTempFlavor = () => {
    tempFlavorModel.value = {
        name: '',
        isRequired: 0,
        id: null,
        dishId: null,
        values: []
    };
};

const getCategories = async () => {
    let params = {
        pageNo: tableData.value.pageNo,
        pageSize: 9999,
    }

    Object.assign(params, searchForm.value)
    let result = await proxy.Request({
        url: api.getCategories,
        params,
    })

    if (!result) {
        return
    }
    Object.assign(categoriesData.value, result.data.list)
}

// 菜品列表数据
const loadDataList = async () => {
    let params = {
        pageNo: tableData.value.pageNo,
        pageSize: tableData.value.pageSize,
    }

    Object.assign(params, searchForm.value)
    let result = await proxy.Request({
        url: api.loadDataList,
        params,
    })

    if (!result) {
        return
    }

    Object.assign(tableData.value, result.data)

    console.log(result);

}

const tableInfoRef = ref()

// 重置方法
const reset = () => {
    searchForm.value = {
        nameFuzzy: '',
        descriptionFuzzy: '',
        status: ''
    }
    loadDataList()
}

// 新增修改操作
const formDialogRef = ref(null)
const formDialogFlaRef = ref(null)
const dialogTitle = ref('')
const dialogFlaTitle = ref('')


const formModel = ref({
    flavors: {
        values: []
    }
})

const rules = {
    categoryId: [{ required: true, message: '请选择菜品分类', trigger: 'change' }],
    name: [{ required: true, message: '菜品名称不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
    sortOrder: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
    originalPrice: [
        { required: true, message: '原价不能为空', trigger: 'blur' },
        { type: 'number', min: 0, message: '原价必须大于等于0', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '现价不能为空', trigger: 'blur' },
        { type: 'number', min: 0, message: '现价必须大于等于0', trigger: 'blur' }
    ],
    stock: [
        { required: true, message: '库存不能为空', trigger: 'blur' },
        { type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur' }
    ],
};

const flavorRules = {
    name: [{ required: true, message: '口味名称不能为空', trigger: 'blur' }],
    values: [
        {
            validator: (rule, value) => {
                if (!Array.isArray(value) || value.length === 0 || value.some(v => !v || !v.trim())) {
                    return Promise.reject('请添加口味值，且不能为空');
                }
                return Promise.resolve();
            },
            trigger: 'blur'
        }
    ],
    isRequired: [{ required: true, message: '请选择是否必选', trigger: 'change' }]
};



// 新增或修改按钮
const openAddOrUpdata = (row) => {
    // 获取分类
    getCategories()
    if (row == null) {
        dialogTitle.value = '新增菜品'
        formModel.value = {
            sortOrder: 0,
            name: '',
            description: '',
            price: 0,
            originalPrice: 0,
            stock: 1,
            flavors: {
                values: []
            },
        }
        fileList.value = []       // 清空图片列表
        nextTick(() => formDialogRef.value.open('bounce'))
    } else {
        dialogTitle.value = '编辑菜品'
        formModel.value = { ...row }
        tempFlavorModel.value = {
            name: row.dishFlavors.name,
            id: row.dishFlavors.id,
            dishId: row.dishFlavors.dishId,
            isRequired: 0,
            values: row.dishFlavors.values
        };

        formModel.value.flavors = JSON.stringify(tempFlavorModel.value);


        // 图片赋值
        fileList.value = row.attachment?.map(img => ({
            id: img.id,       // 数据库已有 ID
            url: `data:${img.fileType};base64,${img.fileUrl}`, // base64
            raw: null         // 原文件为 null，表示未修改
        })) || []

        nextTick(() => formDialogRef.value.open('bounce'))
    }
}

// 新增口味
const addFlavors = () => {
    if (addFlavors == null) {
        dialogFlaTitle.value = '新增口味'
        nextTick(() => formDialogFlaRef.value.open('bounce'))
    } else {
        dialogFlaTitle.value = '编辑口味'
        nextTick(() => formDialogFlaRef.value.open('bounce'))
    }

}

// 新增口味值
const addFlavorValue = () => {
    if (!tempFlavorModel.value) {
        tempFlavorModel.value = {
            name: '',
            isRequired: 0,
            id: null,
            dishId: null,
            values: []
        };
    } else if (!Array.isArray(tempFlavorModel.value.values)) {
        tempFlavorModel.value.values = [];
    }
    tempFlavorModel.value.values.push('');
};

// 删除口味值
const removeFlavorValue = (index) => {
    if (tempFlavorModel.value && Array.isArray(tempFlavorModel.value.values)) {
        tempFlavorModel.value.values.splice(index, 1);
    }
};

const handleFlaSubmit = async () => {
    // 保存到菜品表单
    formModel.value.flavors = JSON.stringify(tempFlavorModel.value);
    formDialogFlaRef.value.close()
}

const handleSubmit = async () => {
    try {
        let params = Object.assign(formModel.value)
        const result = await proxy.Request({
            url: api.addOrUpdate,
            params
        })
        if (result && result.code === 200) {
            proxy.$message.success('操作成功')
            formDialogRef.value.close()  // 请求成功才关闭
            await getImageArray(result.data)
            // loadDataList()               // 刷新列表
        } else {
            proxy.$message.error(result?.msg || '操作失败')
        }
    } catch (error) {
        proxy.$message.error('请求异常，请重试')
        console.error(error)
    }
    console.log("最后的值", formModel.value);

}

const fileList = ref([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const disabled = ref(false)

const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}

// 新增删除图片集合
const deletedFiles = ref([])

const handleRemove = (file) => {
    // 如果是数据库已有图片，记录到 deletedFiles
    if (file.id) {
        deletedFiles.value.push(file)
    }
    // 从 fileList 中移除
    const index = fileList.value.indexOf(file)
    if (index !== -1) fileList.value.splice(index, 1)
}

// 获取图片数组的方法
const getImageArray = async (value) => {
    const formData = new FormData();

    formData.append("id", value);

    // 遍历 fileList 添加新文件或已有文件的 id
    fileList.value.forEach(file => {
        if (file.raw) {  // 新上传文件
            formData.append('file', file.raw);
        }
    });

    // 遍历 deletedFiles 添加被删除文件的 id
    deletedFiles.value.forEach(file => {
        formData.append('deletedAttachmentIds', file.id);
    });

    try {
        await axios.post(api.uploadFile, formData);
        resetFormModel() // 重置表单数据
        loadDataList()
    } catch (error) {
        console.error("图片上传失败", error);
    }
}

// 菜品上下架
const dishesStatus = async (id, status) => {
    let url = api.disable
    const params = {
        id
    }
    // 上架
    if (status === 1) {
        url = api.enable
    }

    let result = await proxy.Request({
        url,
        params,
    })
    if (result && result.code === 200) {
        loadDataList()
        proxy.$message.success('操作成功')
    }

}

const handleAudSubmit = async (id) => {
    dialogAudTitle.value = '审核结果'
    // 获取审核信息
    let result = await proxy.Request({
        url: api.getAudit,
        params: {
            id
        }
    })
    console.log("获取审核结果", result);
    if (result.code === 200) {
        AuditModel.value = result.data
    }
    nextTick(() => formDialogAudRef.value.open('bounce'))
}

const handleAuditSubmit = () => {
    formDialogAudRef.value.close()
}

// 删除菜品
const delDishesBtn = async (id) => {
    proxy.Confirm('确定删除菜品吗？', async () => {
        let result = await proxy.Request({
            url: api.delDishes,
            params: {
                id
            }
        })
        if (result != null && result.code === 200) {
            proxy.$message.success('删除成功')
            loadDataList()
        }
    })
}
</script>

<style lang="scss" scoped>
.detail-tree-panel {
    height: calc(100vh - 273px);
    overflow: auto;
    width: 100%;
}
</style>